package hyl.base.flow;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import hyl.base.flow.dao.HylFlowDao;
import hyl.core.Amy;
import hyl.core.MyFun;
import hyl.core.conf.MyConfig;
import hyl.core.db.MyDB;
import hyl.core.io.MyFile;
import hyl.core.io.MyPath;

/**
 * 缓存了所有用到的工作流模型
 */

public class PoolFlow {
	private HylFlowDao _fd;
	MyDB _db;
	static PoolFlow _cfp;

	public HylFlowDao getFlowDao() {
		return _fd;
	}
	/*
	 * public void commit() { _db.commit(); }
	 */

	// 初始化
	/**
	 * 默认是在flow 文件夹下 指定配置文件名所在目录,如果不指定,从默认程序类的根目录读取
	 */
	public static PoolFlow getInstance(String dir) {
		if (_cfp == null) {
			_cfp = new PoolFlow();
			_cfp.loadConfig(dir);
		}
		return _cfp;
	}

	public static PoolFlow getInstance() {
		if (_cfp == null) {
			_cfp = new PoolFlow();
			_cfp.loadConfig(null);
		}
		return _cfp;
	}

	// 流模型池子
	public Map<String, Flow> _flows = new HashMap<>();

	public Flow getFlowModel(String key) {
		return _flows.get(key);
	}

	// 流配置目录
	private static final String rootpath = MyPath.getPathOfClass(PoolFlow.class, "/flow/");

	// 载入配置
	private void loadConfig(String path) {

		if (MyFun.isEmpty(path))
			path = rootpath;
		File dir = MyFile.openDir(path);
		for (File f : dir.listFiles()) {
			if (!f.getName().endsWith(".flow"))
				continue;
			// System.out.println(f.getName());

			Map<String, Object> conf = MyConfig.loadJson(f, null);
			String name = conf.get("name").toString();
			String track = conf.get("track").toString();
			Object links = conf.get("links");
			// _db = Amy.getTimerDb1();
			_db = Amy.createCommitDb();
			_fd = new HylFlowDao(_db);
			Flow flow = new Flow(this, name, track, links);
			_flows.put(name, flow);

			// ???

		}
		System.out.println("flow配置已加载完成..");
		// MyFile.openDir(path)
		// MyConfig.loadJson(filename, encode)
	}

}
